<template>
  <div class="search-container">
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <search-result
      v-if="isResultShow"
      :search-text="searchText"
    ></search-result>

    <search-suggestion
      @search="onSearch"
      v-else-if="searchText"
      :search-text="searchText"
    ></search-suggestion>

    <search-history
      v-else
      :searchHistories="searchHistories"
      @clear-search-histories="searchHistories = []"
      @search="onSearch"
    ></search-history>
  </div>
</template>
<script>
import searchHistory from "./components/search-history.vue";
import searchSuggestion from "./components/search-suggestion.vue";
import searchResult from "./components/search-result.vue";
import { setItem, getItem } from "@/utils/storage";
export default {
  name: "SearchIndex",
  components: { searchHistory, searchSuggestion, searchResult },
  props: {},
  data() {
    return {
      searchText: "",
      isResultShow: false,
      searchHistories: getItem("TOUTIAO_SEARCH_HISTORY") || [],
    };
  },
  computed: {},
  watch: {
    searchHistories(value) {
      // 同步搜索数据到本地
      setItem("TOUTIAO_SEARCH_HISTORY", value);
    },
  },
  created() {},
  mounted() {},
  methods: {
    onSearch(val) {
      this.searchText = val;
      const index = this.searchHistories.indexOf(val);
      if (index !== -1) {
        this.searchHistories.splice(index, 1);
      }
      this.searchHistories.unshift(val);
      this.isResultShow = true;
    },
    onCancel() {
      this.$router.back();
    },
  },
};
</script>
<style scoped lang='less'>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>